package org.jeecg.modules.demo.task.controller;

import java.util.*;
import java.util.concurrent.ScheduledFuture;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.Data;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.task.entity.TTask;
import org.jeecg.modules.demo.task.manager.DynamicTaskManager;
import org.jeecg.modules.demo.task.service.ITTaskService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: t_task
 * @Author: jeecg-boot
 * @Date:   2025-04-14
 * @Version: V1.0
 */
@Api(tags="t_task")
@RestController
@RequestMapping("/task/tTask")
@Slf4j
public class TTaskController extends JeecgController<TTask, ITTaskService> {
	@Autowired
	private ITTaskService tTaskService;
	@Resource
	private DynamicTaskManager dynamicTaskManager;
	
	/**
	 * 分页列表查询
	 *
	 * @param tTask
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "t_task-分页列表查询")
	@ApiOperation(value="t_task-分页列表查询", notes="t_task-分页列表查询")

	@GetMapping(value = "/list")
	public Result<IPage<TTask>> queryPageList(TTask tTask,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
        // 自定义查询规则
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
        // 自定义多选的查询规则为：LIKE_WITH_OR
        customeRuleMap.put("taskTime", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("type", QueryRuleEnum.LIKE_WITH_OR);
        QueryWrapper<TTask> queryWrapper = QueryGenerator.initQueryWrapper(tTask, req.getParameterMap(),customeRuleMap);
		if (!loginUser.getRoleCode().contains("admin")){
			queryWrapper.eq("user_id",loginUser.getId());
		}
		Page<TTask> page = new Page<TTask>(pageNo, pageSize);
		IPage<TTask> pageList = tTaskService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param tTask
	 * @return
	 */
	@AutoLog(value = "t_task-添加")
	@ApiOperation(value="t_task-添加", notes="t_task-添加")
	@RequiresPermissions("task:t_task:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody TTask tTask) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		tTask.setUserId(loginUser.getId());
		tTask.setCreateTime(new Date().getTime());
		tTaskService.save(tTask);
		dynamicTaskManager.startTask(tTask);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param tTask
	 * @return
	 */
	@AutoLog(value = "t_task-编辑")
	@ApiOperation(value="t_task-编辑", notes="t_task-编辑")
	@RequiresPermissions("task:t_task:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody TTask tTask) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		TTask byId = tTaskService.getById(tTask.getId());
		if (!loginUser.getRoleCode().contains("admin")){
			if (!byId.getUserId().equals(loginUser.getId())){
				return Result.error("请勿修改其他用户的信息");
			}
		}
		tTask.setUpdateTime(new Date().getTime());
		tTaskService.updateById(tTask);
		Map<Long, ScheduledFuture<?>> futureMap = dynamicTaskManager.findFutureMap();
		if (tTask.getType()==1){

			if (!futureMap.containsKey(tTask.getId())){
				dynamicTaskManager.startTask(tTask);
			}
		}else{
			if (futureMap.containsKey(tTask.getId())){
				dynamicTaskManager.stopTask(tTask.getId());
			}
		}
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "t_task-通过id删除")
	@ApiOperation(value="t_task-通过id删除", notes="t_task-通过id删除")
	@RequiresPermissions("task:t_task:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		TTask tTask = tTaskService.getById(id);
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if (!loginUser.getRoleCode().contains("admin")){
			if (!tTask.getUserId().equals(loginUser.getId())){
				return Result.error("请勿修改其他用户的信息");
			}
		}
		tTaskService.removeById(id);
		Map<Long, ScheduledFuture<?>> futureMap = dynamicTaskManager.findFutureMap();
		if (futureMap.containsKey(tTask.getId())){
			dynamicTaskManager.stopTask(tTask.getId());
		}
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "t_task-批量删除")
	@ApiOperation(value="t_task-批量删除", notes="t_task-批量删除")
	@RequiresPermissions("task:t_task:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.tTaskService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "t_task-通过id查询")
	@ApiOperation(value="t_task-通过id查询", notes="t_task-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<TTask> queryById(@RequestParam(name="id",required=true) String id) {
		TTask tTask = tTaskService.getById(id);
		if(tTask==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(tTask);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param tTask
    */
    @RequiresPermissions("task:t_task:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TTask tTask) {
        return super.exportXls(request, tTask, TTask.class, "t_task");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("task:t_task:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TTask.class);
    }

}
